import { Alert } from 'antd';
import React, { useEffect, useMemo, useReducer } from 'react';
import { useParams } from "react-router-dom";
import client from '../utils/client';
import MpComponent from './MpComponent';
import MetaPlatformForm from './MpForm';
import MetaPlatformPage from './MpPage';
import styles from './page.module.css';

function Page({ id, args, menuId, tabs }) {
  const params = useParams();

  const [state, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case 'loaded':
        return { ...state, loading: false, ...action.page };
      default:
        return state;
    }
  }, {
    id: id || params.id,
    loading: true,
    method: null,
    content: null,
    args: null,
  });

  useEffect(() => {
    client.job('B.PageInfoGet', { PID: state.id, MID: menuId }).then(page => {
      dispatch({
        type: 'loaded',
        page: !page ? {} : {
          method: page.解析方式,
          content: page.解析内容,
          args: page.解析参数 ? JSON.parse(page.解析参数) : {},
          metatype: page.元数据类型,
          metadata: page.元数据 ? JSON.parse(page.元数据) : undefined,
        }
      });
    });
    // eslint-disable-next-line
  }, []);

  const children = useMemo(() => {
    if (state.loading) return null;
    const searchParams = Object.fromEntries(new URLSearchParams(window.location.search));
    const props = Object.assign(state.args, searchParams, args);
    switch (state.method) {
      case 0: // 内置页面
        return <MpComponent name={state.content} {...props} tabs={tabs} />;
      case 1: // 元数据页面
        if (!state.metadata) return <Alert showIcon message="页面解析失败" description="元数据不存在" type="error" />;
        switch (state.metatype) {
          case 'page': return <MetaPlatformPage {...props} metadata={state.metadata} tabs={tabs}></MetaPlatformPage>;
          case 'form': return <MetaPlatformForm {...props} metadata={state.metadata} tabs={tabs}></MetaPlatformForm>;
          case 'table':
          default: return <Alert showIcon message="页面解析失败" description={`未知的元数据类型: ${state.metatype}`} type="error" />;
        }
      case 2: // 集成外部页面
        const token = client.get('TOKEN');
        const user = client.get('user');
        const url = state.content + (state.content.includes('?') ? '&' : '?') + `uid=${user ? user.ID : ''}&token=${token}`;
        return <div style={{ flex: 1, display: 'flex' }}><iframe style={{ flex: 1, border: 'none' }} title={url} src={url} /></div>;
      case 3: // 外部页面
        return <div style={{ flex: 1, display: 'flex' }}><iframe style={{ flex: 1, border: 'none' }} title={state.content} src={state.content} /></div>;
      default:
        return <Alert showIcon message="页面解析失败" description="未能识别解析方式" type="error" />;
    }
  }, [args, state.metadata, state.metatype, state.args, state.content, state.method, tabs, state.loading]);

  return <div className={styles.container}>{children}</div>
}

export default Page;